package com.pi.pro.xcmg.am.was.web.cust.controller;





import com.pi.common.CodesConstants;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.pro.xcmg.am.common.vo.act.PickLabelDto;
import com.pi.pro.xcmg.am.was.fac.service.WasCustomWorkService;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.entity.TwtActTaskList;
import com.pi.wms.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Controller
@RequestMapping("/task/pktask/ca")
public class CustApplyPkTasklistsController extends BaseCrudController<TwtActTaskList, Long> {

	@Autowired
	protected TaskService service;

	@Autowired
	private WasCustomWorkService wasCustomWorkService;

	@Override
	protected ICrudService<TwtActTaskList, Long> getCrudService() {
	    return service;
	}

	@Override
	protected String getPrefix() {
		return "pktask";
	}

	@Override
	protected TwtActTaskList newModel(HttpServletRequest request) {
		return new TwtActTaskList();
	}

	@Override
	protected void prepareDatatableConditions(Map<String, Object> query, DataTablesInput input) {
		Long userId = SecurityUtils.getLoginUserId();
		query.put("userId", userId.toString());
		query.put("tasktype", WmsConstants.TASK_TYPE_PICK);
		query.put("showcancel", CodesConstants.COMMON_FLAG_NO);
		super.prepareDatatableConditions(query, input);
	}

	@PostMapping("confirm")
	public String confirm(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		model.addAttribute("params", getParams(request));
		String m="";
		TwtActTaskList task=null;
		if ((ids == null) || (ids.length==0)) {
            addSuccessMessage(redirectAttributes, "确认拣货成功");
			return this.redirect("");
		}
		Map<String,String> nums=new HashMap<>();
		List<TwtActTaskList> tasks=new ArrayList<>();
        for (Long id : ids) {
            task = service.findById(id);
            if (task == null) {
                continue;
            }
            if (this.wasCustomWorkService.closed(task)){
				addErrorMessage(redirectAttributes, "任务已经完成.任务号:"+task.getNumber());
				return this.redirect("");
			}
			if (!WmsConstants.TASK_TYPE_PICK.equalsIgnoreCase(task.getType())){
                addErrorMessage(redirectAttributes, "非拣货任务.任务号:"+task.getNumber());
                return this.redirect("");
            }
            if (task.getRefAllocationId()==null){
                addErrorMessage(redirectAttributes, "非有效拣货任务.任务号:"+task.getNumber());
                return this.redirect("");
            }
            if (nums.containsKey(task.getNumber())){
                continue;
            }
            m=this.wasCustomWorkService.shipmentByAllocationId(task.getRefAllocationId(), task.getFromContainNumber(), SecurityUtils.getLoginUsername());
            if (!StringUtils.isNullOrBlank(m)){
                addErrorMessage(redirectAttributes, "确认发货失败.任务号:"+task.getNumber()+".异常:"+m);
                return this.redirect("");
            }
            nums.put(task.getNumber(), CodesConstants.PROCESS_FAIL_FAST);
        }
        addSuccessMessage(redirectAttributes, "确认拣货成功");
		return this.redirect("");
	}

	@PostMapping("printlabel")
	public String printLabel(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
							 RedirectAttributes redirectAttributes) {

		model.addAttribute("params", getParams(request));
		if ((ids==null) || (ids.length==0)){
			addErrorMessage(redirectAttributes, "请选定打印数据.");
			return this.redirect("");
		}
		String m="";
		TwtActTaskList task=null;
        PickLabelDto labelData=null;
		try{
			for (Long id:ids){
				if (id==null) {
					continue;
				}
                task=this.service.findById(id);
				if (this.wasCustomWorkService.closed(task)){
				    continue;
                }
                labelData=this.wasCustomWorkService.createPickLabel(task);
				m = this.wasCustomWorkService.printPickLabel(task, labelData);
				if (!StringUtils.isNullOrBlank(m)) {
					addErrorMessage(redirectAttributes, "打印失败:"+m);
					return this.redirect("");
				}
			}
		}catch (Exception e){
			m="发送打印任务失败.错误:"+e.getMessage();
			e.printStackTrace();
		}
		if(!StringUtils.isNullOrBlank(m)){
			addErrorMessage(redirectAttributes, "发送打印任务失败:"+m);
			return this.redirect("");
		}
		addSuccessMessage(redirectAttributes, "发送打印任务成功");
		return this.redirect("");
	}

	//
	protected String redirect(String relativeUrl) {
		if(!StringUtils.isNullOrBlank(relativeUrl) && !relativeUrl.startsWith("/")) {
			relativeUrl = "/" + relativeUrl;
		}
		return "redirect:" + this.referUrl() + relativeUrl;
	}

	private String referUrl(){
		return "/task/pktask/";
	}


}
